// src/api/fundApi.js

/**
 * 本文件定义了与基金行情相关的所有前端 API 调用
 */

import http from '../utils/http';  // 你已有的 axios 实例，自动带 baseURL + token 拦截
import axios from 'axios';

/**
 * 获取基金列表
*/
export async function   $fetchFundList() {
    const res=await axios.get('/api/fund/list');
    let body=res.data;
    console.log('响应数据:', body);
    // 如果 backend 将整个 body 当字符串返回
  if (typeof body === 'string') {
    const cleaned = body.replace(/\bNaN\b/g, 'null')
    try {
      body = JSON.parse(cleaned)
    } catch (e) {
      throw new Error(`响应非 JSON 格式：${cleaned}`)
    }
  }
  // 如果 body.data 是字符串，也需要 parse
  if (body && typeof body === 'object' && typeof body.data === 'string') {
    const cleanedData = body.data.replace(/\bNaN\b/g, 'null')
    try {
      body.data = JSON.parse(cleanedData)
    } catch (e) {
      throw new Error(`data 字段非 JSON 格式：${cleanedData}`)
    }
  }

  // 兼容纯数组或 { code, data } 对象
  if (Array.isArray(body)) {
    return body
  }
  if (body && typeof body === 'object' && typeof body.code !== 'undefined') {
    if (body.code === 0 && Array.isArray(body.data)) {
      return body.data
    }
    throw new Error(`业务异常：code=${body.code}, msg=${body.msg || '无'}`)
  }

  throw new Error(`返回格式不符合预期：${JSON.stringify(body)}`)
}



export async function $fetchFundTrend(symbol) {
  const res = await axios.get('/api/fund/trend', { params: { symbol } 
  }).then(res=>res.data);

  let body = res;
  console.log('响应数据:', body);

  // 如果 backend 将整个 body 当字符串返回
if (typeof body === 'string') {
  const cleaned = body.replace(/\bNaN\b/g, 'null')
  try {
    body = JSON.parse(cleaned)
  } catch (e) {
    throw new Error(`响应非 JSON 格式：${cleaned}`)
  }
}

// 如果 body.data 是字符串，也需要 parse
if (body && typeof body === 'object' && typeof body.data === 'string') {
  const cleanedData = body.data.replace(/\bNaN\b/g, 'null')
  try {
    body.data = JSON.parse(cleanedData)
  } catch (e) {
    throw new Error(`data 字段非 JSON 格式：${cleanedData}`)
  }
}



// 兼容纯数组或 { code, data } 对象
if (Array.isArray(body)) {
  return body
}
if (body && typeof body === 'object' && typeof body.code !== 'undefined') {
  if (body.code === 0 && Array.isArray(body.data)) {
    return body.data
  }
  throw new Error(`业务异常：code=${body.code}, msg=${body.msg || '无'}`)
}

throw new Error(`返回格式不符合预期：${JSON.stringify(body)}`)
}


/**
 * 购买基金
 * @param {Object} data - 购买数据
 * @returns {Promise<Object>}
 */
export const $buyFund = async (data) => {
  try {
      const response = await axios.post('/api/fund/buy', data);
      return response.data;
  } catch (error) {
      throw error.response?.data || { msg: '购买失败' };
  }
};

/**
* 售出基金
* @param {Object} data - 售出数据
* @returns {Promise<Object>}
*/
export const $sellFund = async (data) => {
  try {
      const response = await axios.post('/api/fund/sell', data);
      return response.data;
  } catch (error) {
      throw error.response?.data || { msg: '售出失败' };
  }
};